package definite.Guide.Book.Chap01_02;

import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.FocusTraversalPolicy;
import java.awt.GridLayout;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SortingFocusTraversalPolicy;

public class NextComponentSample {

	public static void main(String[] args) {
		Runnable runner = new Runnable() {

			@Override
			public void run() {

				JFrame frame = new JFrame("Reverse Sample");
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

				GridLayout layout = new GridLayout(3, 3);
				frame.setLayout(layout);

				for (int i = 9; i >= 1; i--) {
					JButton button = new JButton(Integer.toString(i));
					frame.add(button, 0);
				}

				final Container contentPane = frame.getContentPane();
				Comparator<Component> comparator = new Comparator<Component>() {

					@Override
					public int compare(Component o1, Component o2) {
						Component[] components = contentPane.getComponents();
						List list = Arrays.asList(components);
						int first = list.indexOf(o1);
						int second = list.indexOf(o2);
						return second - first;
					}

				};

				FocusTraversalPolicy policy = new SortingFocusTraversalPolicy(
						comparator);
				frame.setFocusTraversalPolicy(policy);
				frame.setSize(300, 200);
				frame.setResizable(false);
				frame.setLocationRelativeTo(null);
				frame.setVisible(true);
			}
		};// end of runnable

		EventQueue.invokeLater(runner);
	}

}
